//
//  NickViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/7/10.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "NickViewController.h"
#import "TPKeyboardAvoidingTableView.h"
#import "PersonalDataVCtrol.h"
#import "IGGetMyinfoApi.h"
#import "IGUpdateNikeApi.h"

@interface NickViewController () <UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate> {
    UITextField * _textfiled;
}

@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *table;
@property(nonatomic,strong)IGGetMyinfoApi *myinfoApi;
@property(nonatomic,strong)IGUpdateNikeApi *updateNickApi;
@end

@implementation NickViewController
#define MaxLength 10
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"更改昵称";
    self.title = NSLocalizedString(@"Change Nickname", nil);
    self.table.backgroundColor=[UIColor c3Color];
    self.automaticallyAdjustsScrollViewInsets = NO;

//    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sure:)];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Confirm", nil) style:UIBarButtonItemStylePlain target:self action:@selector(sure:)];
    [right setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor appColor]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = right;
    self.table.scrollEnabled = NO;
  
}

#pragma mark — UITableViewDataSource, UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    CGFloat x = cell.separatorInset.left;
    cell.backgroundColor=[UIColor c3Color];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UITextField *textView = [[UITextField alloc] initWithFrame:CGRectMake(x, 15, KSCREENWIDTH-2*x, 40)];
      _textfiled =textView;
    textView.delegate=self;
    textView.borderStyle = UITextBorderStyleRoundedRect;
    textView.font = [UIFont systemFontOfSize:14];
    textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    textView.layer.borderWidth = 1;
    textView.clearButtonMode = UITextFieldViewModeWhileEditing;
    [textView addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [textView addTarget:self action:@selector(textBeainEditing:) forControlEvents:UIControlEventEditingDidBegin];
    [textView addTarget:self action:@selector(textEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
    textView.tag = indexPath.row;
//    textView.placeholder = @"请输入昵称";
    textView.placeholder = NSLocalizedString(@"Nickname", nil);
    textView.text = self.nick;
    textView.tag = 0;
    textView.keyboardType = UIKeyboardTypeDefault;
    [cell.contentView addSubview:textView];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 30)];
    UILabel *foot = [[UILabel alloc] initWithFrame:CGRectMake(tableView.separatorInset.left, 0, tableView.width, 30)];
    foot.font = [UIFont systemFontOfSize:14];
    foot.textColor = [UIColor grayColor];
//    foot.text = @"好名字让你更容易被认知";
    foot.text = NSLocalizedString(@"A Good Name , A Big Impression", nil);
    [view addSubview:foot];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 2.0f;
}

- (void)textBeainEditing:(UITextField *)textView
{
    self.table.bounces = YES;
}

- (void)textEndEditing:(UITextField *)textView
{
    self.table.bounces = NO;
}

- (void)textChange:(UITextField *)textView
{
    NSString *toBeString=textView.text;
    UITextRange *selectedRang=[textView markedTextRange];
    UITextPosition *position=[textView positionFromPosition:selectedRang.start offset:0];
    if (!position) {
        NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000 );
        NSData *da=[toBeString dataUsingEncoding:enc];
        NSInteger dataLength=[da length];
        if(dataLength>20){
            int lll=(int)[toBeString length];
            for (int z=0; z<lll; z++) {
                NSString *fromString=[toBeString substringToIndex:z];
                NSStringEncoding enc2=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
                NSData *da2FROM=[fromString dataUsingEncoding:enc2];
                NSInteger fromDataLength2=[da2FROM length];
                if (fromDataLength2==20) {
                    textView.text=fromString;
                }
                if (fromDataLength2>20) {
//                    [self presentMessageTips:@"昵称最多10个字"];
                    [self presentMessageTips:NSLocalizedString(@"No more than 10 characters", nil)];
                    return;
                }
            }
        }
        else{
            textView.text=toBeString;
        }
    }
    _nick = textView.text;
}

- (void)sure:(UIBarButtonItem *)btn
{
    [self.view endEditing:YES];
    if (self.nick.length == 0) {
//        [self presentMessageTips:@"请输入昵称"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Nickname", nil)];
        return;
    }
    
    BOOL ishas = [NSString stringContainsEmoji:self.nick];
    if (ishas) {
//        [self presentMessageTips:@"不支持表情符号"];
        [self presentMessageTips:NSLocalizedString(@"Emoji Unavailable", nil)];
        return;
    }
    self.updateNickApi=[[IGUpdateNikeApi alloc]initWithUid:[IGUser getUid] nike:_textfiled.text];

    [self.updateNickApi startWithDecodeClass:[IGUpdateNikeResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
      if (responseObject) {
           [IGUser saveNike:_textfiled.text];
          [self.navigationController popViewControllerAnimated:YES];
      }
  }];
}

-(void)pushVC
{
    PersonalDataVCtrol *pVC = [[PersonalDataVCtrol alloc] init];
    [self.navigationController pushViewController:pVC animated:YES ];
    BOOL flag = NO;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < self.navigationController.viewControllers.count - 1; i ++)
    {
        UIViewController *vc = self.navigationController.viewControllers[i];
        if (flag == NO && [vc isKindOfClass:[PersonalDataVCtrol class]])
        {
            flag = YES;
        }
        if (flag)
        {
            [array addObject:vc];
        }
    }
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    [viewControllers removeObjectsInArray:array];
    self.navigationController.viewControllers = viewControllers;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [_textfiled resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}



@end
